package org.bminfo.sequence;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.yaml.snakeyaml.Yaml;

public class RawInput {

	/** 
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		RawInput in = new RawInput();
		System.out.println(in.GetFullTextForWebControl(".\\WebContent\\data\\genbank.txt"));
	}

	/*
	 * Definition: this function return full text of article with double
	 * 				backslash at the end of each line.
	 * Input: infilePath
	 * Output: content with double backslash at the end of line
	 */
	public String GetFullTextForWebControl(String infilePath){
		File finput = new File(infilePath);
		BufferedReader br1 = null;
		try {
			br1 = new BufferedReader(new InputStreamReader(new FileInputStream(finput)));
		} catch (FileNotFoundException e) {
			System.err.println("Error in RawInput:GetFullTextWithDoubleBackSlash: Could no find the file: " + infilePath);
			e.printStackTrace();
		}
		String line = null;
		StringBuffer lines = new StringBuffer();
		try {
			while((line = br1.readLine()) != null){
				lines.append(line + "\\n");
			}
			br1.close();
		} catch (IOException e) {
			System.err.println("Error in RawInput:GetFullTextWithDoubleBackSlash: Could no read the file: " + infilePath);
			e.printStackTrace();
		}
		
		return lines.toString().replace("\"","\\\"").replace("\'","\\\'");
	}

	public String GetFullText(String infilePath ){
		// TODO Auto-generated method stub
		BufferedReader fFile = null;
		String line = new String();
		String content =new String();
		try {
			fFile = new BufferedReader(new FileReader(infilePath));
			try {
				while ((line = fFile.readLine()) != null) {
					content += line +"\n";
				}
			} catch (IOException e) {
				e.printStackTrace();
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.err.println("In RawInput.ReadFullText Could not open " + infilePath);
		}

		return content;
	}

	public ArrayList<String> GetListByEachLine(String infilePath, boolean keepBlankLine ){
		// TODO Auto-generated method stub
		BufferedReader fFile = null;
		String line = new String();
		//		String content =new String();
		ArrayList<String> cntList = new ArrayList<String>();
		try {
			fFile = new BufferedReader(new FileReader(infilePath));
			try {
				while ((line = fFile.readLine()) != null) {
					//				content += line +"\n";
					line.trim();
					if(line.length() == 0 && (!keepBlankLine))
						continue;

					cntList.add(line);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return cntList;
	}


	public String GetInput() {
		// TODO Auto-generated method stub
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		String input = null;

		// read the username from the command-line; need to use try/catch with
		// the
		// readLine() method
		try {
			input = br.readLine();
		} catch (IOException ioe) {
			System.out.println("IO error trying to read your name!"); //$NON-NLS-1$
			System.exit(1);
		}

		return input;
	}

	//http://www.exampledepot.com/egs/java.io/GetFiles.html
	public Boolean GetDirectoryFile(String dirPath, ArrayList<String> fileList) {
		// TODO Auto-generated method stub
		if(!dirPath.endsWith("/"))
		{
			dirPath += "/";
		}

		File dir = new File(dirPath);
		String[] flist = dir.list();

		if(flist == null)
			System.err.println("Could not open the folder or there is no file under it:" + dirPath);

		if(dir == null)
		{
			System.err.println("can not open" + dirPath);
			return false;
		}

		for(int i =0; i<flist.length; i++)
		{
			String name = flist[i]; 
			//			filter .svn/ ./ ../
			if(name.startsWith(".")){
				continue;
			}else{
				String tempname = dirPath + name;
				File subdir = new File(tempname);
				if(subdir.isDirectory() && subdir != null){
					if(!GetDirectoryFile(tempname , fileList))
						System.err.println("Read erro!" + tempname );
				}else{
					fileList.add(dirPath + name);
				}
			}
		}		

		return true;
	}

	public boolean IsFileExist(String fileName) {
		// TODO Auto-generated method stub
		File f = new File(fileName);

		if ( f.exists() )
		{
			return true;
		}
		return false;
	}

	public Object LoadYAMLfile(String yamlfile) {
		// TODO Auto-generated method stub
		Yaml yaml = new Yaml();
		String str = new String();

		String bgnAnnot = "^#(.*)";
		String spbgnAnnot = "\\s+#(.*)";
		String blank = "^$";

		Pattern midAnnot = Pattern.compile("(.*)#(.*)");

		String line = new String();

		Object rlt = null;
		try {
			BufferedReader in = new BufferedReader(new FileReader(yamlfile));

			while ((line = in.readLine()) != null) {

				Matcher ptnMatcher = midAnnot.matcher(line);

				if (line.matches(bgnAnnot))
				{
					continue;
				}else if(line.matches(spbgnAnnot))
				{
					continue;
				}else if(line.matches(blank))
				{
					continue;
				}else if(ptnMatcher.find())
				{

					line = line.replace("#" + ptnMatcher.group(2), "");
				}
				str+=line + "\n";
			}


			in.close();

		} catch (IOException e) {
			System.err.println("Could not open file");
		}
		rlt = yaml.load(str);
		return rlt;
	}

	//	http://www.blogjava.net/mrcmd/archive/2007/10/12/139003.html
	public static boolean delAllFile(String path) {
		boolean flag = false;
		File file = new File(path);
		if (!file.exists()) {
			return flag;
		}
		if (!file.isDirectory()) {
			return flag;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);
				delFolder(path + "/" + tempList[i]);
				flag = true;
			}
		}
		return flag;
	}
	//	   http://www.blogjava.net/mrcmd/archive/2007/10/12/139003.html   
	public static void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); 
			String filePath = folderPath;
			filePath = filePath.toString();
			java.io.File myFilePath = new java.io.File(filePath);
			myFilePath.delete(); 
		} catch (Exception e) {
			e.printStackTrace(); 
		}
	}

	public void copyfile(File src, File dst) throws IOException {
		// TODO Auto-generated method stub
		InputStream in = new FileInputStream(src);
		OutputStream out = new FileOutputStream(dst);

		// Transfer bytes from in to out
		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		in.close();
		out.close();

	}

	public String GetTemporaryFilePath(){
		File tempFile =  null;
		String tempFilePath = null;
		try {
			tempFile = File.createTempFile("jduan", ".xml");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		tempFilePath = tempFile.getAbsolutePath();
		return tempFilePath;
	}
	HashMap<String, BufferedWriter> fileList = new HashMap<String, BufferedWriter>();
	
	public void CreateFile(String outfile) {
		BufferedWriter fout = null;
		try {
			fout = new BufferedWriter(new FileWriter(outfile));
		} catch (IOException e) {
			System.out.println("Erro 0549pm: in RawInput : create file erro");
			e.printStackTrace();
		}
		fileList.put(outfile, fout);
	}
	
	public void WriteFile(String outfile, String content){
		if(fileList.containsKey(outfile)){
			try {
//				fileList.get(outfile).write(content);
				fileList.get(outfile).write(content + "\n");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void CloseFile(String outfile){
		if(fileList.containsKey(outfile)){
			try {
				fileList.get(outfile).close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public String GetInput(String prompt) {
		System.out.println(prompt);
		return GetInput();
	}
	/*
	 * Definition: Get all of file names under one folder. There many be repeat names
	 * 				in the returned ArrayList
	 * 
	 * Input: String: folder name
	 * 
	 * Output: ArrayList<String>: file name with extension name: 
	 */
	public ArrayList<String> GetFileNameList(String folder) {
		ArrayList<String> filePathNameList = new ArrayList<String>();
		this.GetDirectoryFile(folder, filePathNameList );
		
		ArrayList<String> nameList = new ArrayList<String>();
		for(String filePathName: filePathNameList){
			File f = new File(filePathName);
			if(!f.exists())
				System.err.println("RawInput: The input file do not exist: Error: 1325PM");
			nameList.add(f.getName());
		}
		return nameList;
	}

	public HashMap sortHashMapByValue(HashMap<String, Double> dataMap) {

		HashMap map = new LinkedHashMap();


		List yourMapKeys = new ArrayList(dataMap.keySet());
		List yourMapValues = new ArrayList(dataMap.values());
		TreeSet sortedSet = new TreeSet(yourMapValues);
		Object[] sortedArray = sortedSet.toArray();
		int size = sortedArray.length;

		for (int i=0; i<size; i++) {
		   map.put
		      (yourMapKeys.get(yourMapValues.indexOf(sortedArray[i])),
		       sortedArray[i]);
		}
		
		return map;
	}
}
